/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package checker.sdchecker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.Callable;

/**
 *
 * @author takeshi
 */
public class WritePartitionTester extends PartitionTester {

    public static final long ONE_GIG = 1L * 1024 * 1024 * 1024;
    private final long fileSize;
    private volatile long totalSize = -1;

    public WritePartitionTester(File root, int numberOfThreads) throws IOException {
        this(root, numberOfThreads, root.getFreeSpace(), ONE_GIG);
    }

    public WritePartitionTester(File root, int numberOfThreads, long totalSize, long fileSize) throws IOException {
        super(root, numberOfThreads, totalSize);
        this.fileSize = fileSize;
    }

    @Override
    protected Callable<Void> createJob(final File toUse) {
        if (totalSize < 0) {
            totalSize = getTotalSize();
        }
        final long selected = Math.min(totalSize, fileSize);
        totalSize -= selected;
        return new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                long remaining = selected;
                FileOutputStream fout = new FileOutputStream(toUse);
                try {
                    while (remaining > 0 && !isStopped()) {
                        long bytes = Math.min(remaining, TEST_DATA.length);
                        fout.write(TEST_DATA, 0, (int) bytes);
                        fout.flush();
                        addBytes(bytes);
                        remaining -= bytes;
                    }
                    fileFinished();
                } catch (IOException e) {
                    setError(e);
                } finally {
                    fout.close();
                }
                return null;
            }
        };
    }

    @Override
    protected File[] selectFiles(File root) throws IOException {
        int numberOfFiles = (int) (getTotalSize() / this.fileSize);
        if (getTotalSize() % this.fileSize > 0) {
            numberOfFiles++;
        }
        File[] selec = new File[numberOfFiles];
        for (int i = 0; i < selec.length; i++) {
            selec[i] = File.createTempFile("test_data_", ".data", root);
        }
        return selec;
    }

}
